
package com.insigma.business.qrcode.common.dto;


import com.insigma.business.qrcode.common.util.BizCheckUtil;
import com.insigma.business.qrcode.common.vo.QuerySortConEnum;
import com.insigma.business.qrcode.common.vo.ToString;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;


@Getter
public class BaseBSearcher extends ToString {

    
    private int pageNo = 1;

    
    private int pageSize = 20;

    
    private String sortKeyValueJoint;

    
    private int offset;

    
    @Setter
    private long totalCount = -1;

    public BaseBSearcher(int pageNo, int pageSize) {
        this.pageNo = pageNo;
        this.pageSize = pageSize;
        this.offset = (pageNo - 1) * pageSize;
    }

    public BaseBSearcher(int pageNo, int pageSize, String sortKeyValueJoint) {
        this.pageNo = pageNo;
        this.pageSize = pageSize;
        this.sortKeyValueJoint = sortKeyValueJoint;
        this.offset = (pageNo - 1) * pageSize;
    }

    public int getFirst() {
        if (pageNo < 1) {
            pageNo = 1;
        }
        return ((pageNo - 1) * pageSize);
    }

    public String getSortKeyValueJoint() {
        return sortKeyValueJoint;
    }

    public void setSortKeyValueJoint(String sortKeyValueJoint) {
        this.sortKeyValueJoint = sortKeyValueJoint;
    }


    public void setPageNo(int pageNo) {
        this.pageNo = pageNo;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    
    public String getOrderJoint(){
        if(StringUtils.isNotBlank(sortKeyValueJoint)){
            final StringBuilder stringBuilder = new StringBuilder();
            final String[] orderKeyValueArray = sortKeyValueJoint.split("#");
            for(int index=0; index<orderKeyValueArray.length; index++){
                final String orderKeyValue = orderKeyValueArray[index];
                final String[] orderArray = orderKeyValue.split("_");
                BizCheckUtil.checkIsTrue(orderArray.length == 2,"排序条件传入有误");
                BizCheckUtil.checkIsTrue(
                        QuerySortConEnum.getByEnumName(orderArray[1].toUpperCase()) != null,"排序条件传入有误");
                final char[] orderKeyCharArray =  orderArray[0].toCharArray();
                for (char orderKeyChar : orderKeyCharArray) {
                    if (Character.isUpperCase(orderKeyChar)) {
                        stringBuilder.append('_').append(Character.toLowerCase(orderKeyChar));
                    } else {
                        stringBuilder.append(orderKeyChar);
                    }
                }
                stringBuilder.append(" ").append(orderArray[1]);
                if(orderKeyValueArray.length>1 && index+1<orderKeyValueArray.length){
                    stringBuilder.append(", ");
                }
            }
            return stringBuilder.toString();
        }else {
            return null ;
        }
    }

}
